document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchInput');
    const searchButton = document.getElementById('searchButton');
    const articleList = document.querySelector('.article-list');
    const loading = document.getElementById('loading');
    const error = document.getElementById('error');

    // 显示加载动画
    function showLoading() {
        loading.style.display = 'block';
        error.style.display = 'none';
    }

    // 隐藏加载动画
    function hideLoading() {
        loading.style.display = 'none';
    }

    // 显示错误信息
    function showError(msg) {
        error.textContent = msg;
        error.style.display = 'block';
    }

    // 渲染文章列表
    function renderArticles(articles) {
        articleList.innerHTML = '';
        articles.forEach(article => {
            const articleItem = document.createElement('article');
            articleItem.className = 'article-item';

            const img = document.createElement('img');
            img.src = article.imageUrl;
            img.alt = article.title;

            const articleContent = document.createElement('div');
            articleContent.className = 'article-content';

            const title = document.createElement('h3');
            title.textContent = article.title;

            const date = document.createElement('p');
            date.textContent = article.date;

            articleContent.appendChild(title);
            articleContent.appendChild(date);

            articleItem.appendChild(img);
            articleItem.appendChild(articleContent);

            articleList.appendChild(articleItem);
        });
    }

    // 搜索功能
    searchButton.addEventListener('click', () => {
        const searchTerm = searchInput.value.trim();
        if (searchTerm) {
            fetchData(searchTerm);
        } else {
            showError('请输入搜索关键词');
        }
    });

    // 获取数据
    async function fetchData(searchTerm) {
        showLoading();
        try {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 生成伪数据
            const data = [
                {
                    imageUrl: 'https://via.placeholder.com/150',
                    title: `伪数据文章1 - ${searchTerm}`,
                    date: '2023-10-01'
                },
                {
                    imageUrl: 'https://via.placeholder.com/150',
                    title: `伪数据文章2 - ${searchTerm}`,
                    date: '2023-10-02'
                },
                {
                    imageUrl: 'https://via.placeholder.com/150',
                    title: `伪数据文章3 - ${searchTerm}`,
                    date: '2023-10-03'
                }
            ];

            renderArticles(data);
        } catch (err) {
            showError(err.message);
        } finally {
            hideLoading();
        }
    }

    // 初始化页面
    fetchData('');
});